//
//  ModifyPasswordVC.m
//  wanzhaoIM
//
//  Created by liuyuantao on 15/5/6.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "ModifyPasswordVC.h"

#import "MicroDef.h"
#import "JKAlertDialog.h"
#import "CXmppRequestMgr.h"
//#import "CAccountMgr.h"
//#import "CAccountModel.h"
#import "CFolderMgr.h"
#import "UIUtil.h"
#define KTEXTFIELDHEIGHT 50.0f
#define KMARGINHEIGHT 20.0f
#import "MBProgressHUD+WZ.h"
#import "UIBarButtonItem+category.h"


@interface ModifyPasswordVC ()<UITextFieldDelegate>
{
    UITextField *_oldPaswordTF;
    UITextField *_new1PaswordTF;
    UITextField *_new2PaswordTF;
    UIImageView *_errIconImageView;
    UILabel *_errMsgLabel;
}
@end



@implementation ModifyPasswordVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPUPDATEPASSWORD object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:K_XMPPDIDFAILEDRECEIVEIQ object:nil];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changePassword) name:K_XMPPUPDATEPASSWORD object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveFailed) name:K_XMPPDIDFAILEDRECEIVEIQ object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(oldChanged) name:UITextFieldTextDidChangeNotification object:nil];
    // Do any additional setup after loading the view.
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    [self.navigationItem setNewTitleCenter:@"修改密码"];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"call_back" title:@"返回" target:self sel:@selector(back) titleFont:Font18 titleColor:WhiteColor];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:nil title:@"保存" target:self sel:@selector(save) titleFont:Font18 titleColor:WhiteColor];    
    
    __block UIView *superView = self.view;
    
    _oldPaswordTF = [[UITextField alloc] init];
    _oldPaswordTF.placeholder = @"旧密码";
    _oldPaswordTF.backgroundColor = [UIColor clearColor];
    _oldPaswordTF.delegate = self;
    _oldPaswordTF.secureTextEntry = YES;
    _oldPaswordTF.tag = 101;
    _oldPaswordTF.textAlignment = NSTextAlignmentLeft;
    [_oldPaswordTF setBackground:[UIImage imageNamed:@"inputBKIcon1"]];
    [_oldPaswordTF setFont:[UIFont systemFontOfSize:18]];

    [superView addSubview:_oldPaswordTF];
    UILabel *leftLabel1 = [[UILabel alloc] init];
    leftLabel1.backgroundColor = [UIColor clearColor];
    leftLabel1.frame = CGRectMake(0, 0, 15, 1);
    _oldPaswordTF.leftView = leftLabel1;
    _oldPaswordTF.leftViewMode = UITextFieldViewModeAlways;
    
    
    
    _new1PaswordTF = [[UITextField alloc] init];
    _new1PaswordTF.placeholder = @"新密码";
    _new1PaswordTF.tag = 102;
    _new1PaswordTF.delegate = self;
    _new1PaswordTF.backgroundColor = [UIColor clearColor];
    _new1PaswordTF.secureTextEntry = YES;
    _new1PaswordTF.textAlignment = NSTextAlignmentLeft;
    [_new1PaswordTF setBackground:[UIImage imageNamed:@"inputBKIcon2"]];
    [_new1PaswordTF setFont:[UIFont systemFontOfSize:18]];
    
    [superView addSubview:_new1PaswordTF];
    UILabel *leftLabel2 = [[UILabel alloc] init];
    leftLabel2.backgroundColor = [UIColor clearColor];
    leftLabel2.frame = CGRectMake(0, 0, 15, 1);
    _new1PaswordTF.leftView = leftLabel2;
    _new1PaswordTF.leftViewMode = UITextFieldViewModeAlways;
    
    _new2PaswordTF = [[UITextField alloc] init];
    _new2PaswordTF.placeholder = @"确认密码";
    _new2PaswordTF.backgroundColor = [UIColor clearColor];
    _new2PaswordTF.secureTextEntry = YES;
    _new2PaswordTF.tag = 103;
    _new2PaswordTF.delegate = self;
    _new2PaswordTF.textAlignment = NSTextAlignmentLeft;
    [_new2PaswordTF setBackground:[UIImage imageNamed:@"inputBKIcon1"]];
    [_new2PaswordTF setFont:[UIFont systemFontOfSize:18]];
    
    [superView addSubview:_new2PaswordTF];
    UILabel *leftLabel3 = [[UILabel alloc] init];
    leftLabel3.backgroundColor = [UIColor clearColor];
    leftLabel3.frame = CGRectMake(0, 0, 15, 1);
    _new2PaswordTF.leftView = leftLabel3;
    _new2PaswordTF.leftViewMode = UITextFieldViewModeAlways;
    
    
    _errIconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loginErrorImage"]];
    _errIconImageView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_errIconImageView];
    
    _errMsgLabel = [[UILabel alloc] init];
    _errMsgLabel.backgroundColor = [UIColor clearColor];
    [_errMsgLabel setTextColor:RGBCOLOR(0xf4, 0x62, 0x0b)];
    [_errMsgLabel setFont:[UIFont systemFontOfSize:14]];
    [_errMsgLabel setText:@"测试内容"];
    [self.view addSubview:_errMsgLabel];
    
    
    _oldPaswordTF.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, KTEXTFIELDHEIGHT);
    _new1PaswordTF.frame = CGRectMake(0, CGRectGetMaxY(_oldPaswordTF.frame) + KMARGINHEIGHT, HARDWARE_SCREEN_WIDTH, KTEXTFIELDHEIGHT);
    
    _new2PaswordTF.frame = CGRectMake(0, CGRectGetMaxY(_new1PaswordTF.frame) + KMARGINHEIGHT, HARDWARE_SCREEN_WIDTH, KTEXTFIELDHEIGHT);

    _errIconImageView.frame = CGRectMake(15.0f, CGRectGetMaxY(_new2PaswordTF.frame) + 17.5f, _errIconImageView.image.size.width, _errIconImageView.image.size.height);
    
    _errMsgLabel.frame = CGRectMake(CGRectGetMaxX(_errIconImageView.frame) + 6.0f, 0, 150.0f, 44.0f);
    CGPoint cer = _errMsgLabel.center;
    cer.y = _errIconImageView.centerY;
    _errMsgLabel.center = cer;
    
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
 
    [self setErrStatus:NO errorMsg:@"请输入正确的旧密码"];
    
}

-(void)setErrStatus:(BOOL)status errorMsg:(NSString *)errorMsg
{
    if(status)
    {
        [_errIconImageView setImage:[UIImage imageNamed:@"loginErrorImage"]];
        [_errIconImageView setHidden:NO];
        [_errMsgLabel setHidden:NO];
        [_errMsgLabel setText:errorMsg];
    }
    else
    {
        [_errIconImageView setHidden:YES];
        [_errMsgLabel setHidden:YES];
    }
}
- (void)oldChanged
{
    BOOL ret = [self isSameWithOld];
    if (ret) {
        [self setErrStatus:NO errorMsg:@""];
    } else {
        [self setErrStatus:YES errorMsg:@"请输入正确的旧密码"];
    }

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)back
{
    [self.view endEditing:YES];
    
    if (_oldPaswordTF.text.length == 0 || _new1PaswordTF.text.length == 0 || _new2PaswordTF.text.length == 0) {
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    __block ModifyPasswordVC *block = self;
    JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:nil message:@"您修改的信息是否需要保存?"];
    [alert addButton:Button_OK withTitle:@"是" handler:^(JKAlertDialogItem *item) {
        [self save];
    }];
    
    [alert addButton:Button_CANCEL withTitle:@"否" handler:^(JKAlertDialogItem *item) {
        
        [block.navigationController popViewControllerAnimated:YES ];
    }];
    [alert show];
    
    
}


-(void)save
{
    [self.view endEditing:YES];
    
    if (![self isSameWithOld]) {
        
        [self setErrStatus:YES errorMsg:@"请输入正确的旧密码"];
        return;
    }
    if (_new1PaswordTF.text.length==0) {
        [self setErrStatus:YES errorMsg:@"请输入新密码"];
        return;
    }
    if (![self isSurePassword]) {
        [self setErrStatus:YES errorMsg:@"你输入的新密码不一致"];
        return;
    }
    if (_new1PaswordTF.text.length<6) {
        [self setErrStatus:YES errorMsg:@"密码不能小于6位数"];
        return;
    }
    if (![UIUtil isNetworkReachable]) {
        [self setErrStatus:YES errorMsg:@"保存失败,请检查网络"];
        return;
    }
    [UIUtil addMBProgressViewTitle:@"修改中..." inView:self.view alpha:0.5 failureTitle:@"保存失败，请检查网络"];
 
    [[CXmppRequestMgr shareInstance] updatePasswordWithStr:_new1PaswordTF.text];
    
    
}

- (BOOL)isSameWithOld
{
    CAccountModel *acc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    if (_oldPaswordTF.text.length > 0) {
        if ([acc.passWord isEqualToString:_oldPaswordTF.text]) {
            return YES;
        } else {
            return NO;
        }
    } else {
        return NO;
    }
}

- (BOOL)isSurePassword
{
    if (_new1PaswordTF.text.length > 0 && _new2PaswordTF.text.length > 0) {
        if ([_new1PaswordTF.text isEqualToString:_new2PaswordTF.text]) {
            return YES;
        } else {
            return NO;
        }

    } else {
        return NO;
    }
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{
    [self.view endEditing:YES];
}
- (void)saveFailed
{
    [UIUtil hideMBProgressViewForView:self.view];
    [MBProgressHUD showError:@"保存失败,请您检查网路"];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)changePassword
{
    [UIUtil hideMBProgressViewForView:self.view];
    CAccountModel *acc = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    acc.passWord = _new1PaswordTF.text;
    [[CFolderMgr shareInstance].accMgr updateAccount:acc];
    
    [MBProgressHUD showSuccess:@"保存成功"];
    [[CXmppMgr shareInstance] disconnect];
    [[CXmppMgr shareInstance] connect];
     [self.navigationController popViewControllerAnimated:YES];
//    __block ModifyPasswordVC *block = self;
//    JKAlertDialog *alert = [[JKAlertDialog alloc]initWithTitle:@"" message:@"保存成功"];
//    [alert addButton:Button_OK withTitle:@"确定" handler:^(JKAlertDialogItem *item) {
//        [block.navigationController popViewControllerAnimated:YES];
//    }];
//    [alert show];

}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string   // return NO to not change text
{
    [self setErrStatus:NO errorMsg:nil];
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
    }
    if(!M_ISSTRNULL(string))
    {
        
        NSInteger maxLen = 0;
        switch (textField.tag) {
            case 101:
                maxLen = 12;
                break;
            case 102:
                maxLen = 12;
                break;
            case 103:
                maxLen = 12;
                break;
                
            default:
                break;
        }
        
        if([textField.text length] >= maxLen)
        {
            [self setErrStatus:YES errorMsg:@"不能超过12位数"];
            return NO;
        }
    }
    
    return YES;
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
